package net.fdukedom.epicurus.plugin;

import net.fdukedom.epicurus.domain.entity.Plugin;
import net.fdukedom.epicurus.domain.entity.AccessRule;
import net.fdukedom.epicurus.domain.entity.Action;
import net.fdukedom.epicurus.domain.entity.Group;

import java.util.Map;
import java.util.HashMap;
import java.util.Set;

/**
 * @author Dmitry Y. Kochelaev
 */
public class AccessRulesLoader extends CollectionLoader<Plugin, AccessRule> {

    private Map<String, Action> actions;

    private Map<String, Group> groups;

    public AccessRulesLoader(Plugin plugin, Map<String, Group> groups) {
        super(plugin);
        actions = new HashMap<String, Action>();
        this.groups = groups;
        for (Action action : item.getActions()) {
            actions.put(action.getName(), action);
        }
    }

    public AccessRule parseAttributes(Map<String, String> attributes) {
        return new AccessRule(groups.get(attributes.get("group")), actions.get(attributes.get("action")), item, AccessRule.EXECUTE);
    }

    public Set<AccessRule> getLoadedCollection() {
        return item.getAccessRules();
    }

    public void disposeElement(AccessRule element) {
        item.getAccessRules().remove(element);
        element.setAction(null);
        element.setGroup(null);
        element.setPlugin(null);
    }

    public void addElement(AccessRule element) {
        element.setPlugin(item);
        item.getAccessRules().add(element);
     }
}
